package com.sunny.blog.common.config;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sunny.blog.common.annotation.RequiredLogin;
import com.sunny.blog.common.entity.ResponseResult;
import com.sunny.blog.pojo.UserInfoBean;
import com.sunny.blog.service.ICacheService;
import com.sunny.blog.util.CookieUtil;
import com.sunny.blog.util.RedirecUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: BlogInterceptor
 * @Description:
 * @Author: sunt
 * @Date: 2020/4/21 14:46
 * @Version 1.0
 **/
@Component
@Slf4j
public class BlogInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        ResponseResult<Object> result = new ResponseResult<Object>();
        //如果是options请求是cors跨域预请求，设置allow对应头信息
        if (RequestMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        boolean hasLoginAnnotation = method.getMethod().isAnnotationPresent(RequiredLogin.class);
        if (!hasLoginAnnotation) {
            // 不存在LoginRequired注解，则直接通过
            return true;
        }
        RequiredLogin loginRequired = method.getMethod().getAnnotation(RequiredLogin.class);
        // 2.required=false,则无需检查是否登录
        if (loginRequired.required()) {
            String cookieStr = CookieUtil.getCookieStr(request);
            if(StrUtil.isBlank(cookieStr)) {
                RedirecUtil.redirect(request,response,"/admin/login.html");
                //ajax异步请求无法重定向
                // response.sendRedirect("/admin/login.html");
                return false;
            }
            log.info("获取到指定cookie的值:" + cookieStr);
            ICacheService cacheService = this.getBean(ICacheService.class, request);
            UserInfoBean cachUser = (UserInfoBean) cacheService.getObjCacheByCode(cookieStr);
            if(ObjectUtil.isNull(cachUser)) {
                log.info("缓存中用户信息过期");
                RedirecUtil.redirect(request,response,"/admin/login.html");
                return false;
            }
            //校验通过
            return true;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    //获取注入的实体Bean
    private <T> T getBean(Class<T> clazz, HttpServletRequest request) {
        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        return factory.getBean(clazz);
    }
}
